<template>
  <el-dialog
    :close-on-click-modal="false"
    class="business-modal"
    :title="isEdit ? '修改附件' : '新增附件'"
    width="600px"
    :visible.sync="visible"
  >
    <el-form class="edit-people-form" :model="form" :rules="rules" ref="form">
      <el-form-item class="name-label" label="附件类型" prop="accessoryType">
        <el-select clearable v-model="form.accessoryType" class="w330" placeholder="请选择">
          <el-option
            v-for="item in accessoryTypeArr"
            :key="item.value"
            :value="item.value"
            :label="item.title"
          />
        </el-select>
      </el-form-item>

      <!-- <a-form-item class="name-label" label="附件名称">
        <a-input
          class="w330"
          placeholder="请输入"
          v-decorator="['accessoryName', { rules: [{required: true, message: '请输入附件名称'}], validateTrigger: 'change' }]"
        />
      </a-form-item>-->
      <el-form-item label="结束时间" prop="date">
        <el-date-picker
          class="w330"
          placeholder="请选择结束时间"
          value-format="yyyy-MM-dd"
          v-model="form.date"
        />
      </el-form-item>
      <el-upload
        action="https://jsonplaceholder.typicode.com/posts/"
        listType="picture-card"
        :file-list="fileList"
        class="avatar-uploader"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :http-request="customRequest"
      >
        <div>
          <i class="el-icon-plus" size="large" />
        </div>
      </el-upload>
      <preview-modal ref="previewModal" />
    </el-form>
    <div slot="footer">
      <el-button size="large" @click="handleCancel">取消</el-button>
      <el-button
        :disabled="fileList.length === 0"
        size="large"
        type="primary"
        :loading="confirmLoading"
        @click.stop="handleOk"
      >{{ isEdit ? '修改' : '新增' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveOnlyUploads, insertSupplierAccessory } from '@/api/supplier'
import { openNotification, getSession, getDicData, getBase64 } from '@/utils/util'
import PreviewModal from '@/components/PreviewModal'
import pick from 'lodash.pick'

export default {
  components: {
    PreviewModal
  },
  data() {
    return {
      imageUrl: '',
      visible: false,
      isEdit: false,
      form: {
        accessoryType: null,
        date: null
      },
      rules: {
        accessoryType: [{ required: true, message: '请选择附件类型', trigger: 'blur' }],
        date: [{ required: true, message: '请选择结束日期', trigger: 'blur' }]
      },
      confirmLoading: false,
      fileList: [],
      fileArr: [],
      record: this.$route.params.obj || getSession('record'),
      accessoryTypeArr: []
    }
  },
  mounted() {
    if (JSON.stringify(this.$route.params) !== '{}') {
      this.record = this.$route.params.obj
    } else {
      this.record = Object.assign({}, getSession('record'))
    }
    this.accessoryTypeArr = getDicData('002', '002005')
  },
  methods: {
    edit(bool, record) {
      console.log('edit', bool, record)
      this.isEdit = bool
      this.$nextTick(() => {
        this.form = pick(record, 'accessoryType', 'date')
      })
      this.visible = true
    },
    handleOk(e) {
      this.confirmLoading = true

      this.$refs.form.validate(async valid => {
        if (valid) {
          const { accessoryType, date } = this.form
          const validityEndDate = date
          const param = { accessoryType, validityEndDate, createTime: new Date() }
          let paramArr = []
          this.fileList.map(v => {
            paramArr.push({ ...param, uploadId: v.uploadId, supplierCode: this.record.supplierCode })
          })
          console.log('fileArr', paramArr)
          if (this.isEdit) {
            // const res = await updateMenu({ ...param, menuId: values.menuId })
          } else {
            const res = await insertSupplierAccessory(paramArr)
          }
          const mes = this.isEdit ? '修改操作成功' : '新增操作成功'
          openNotification('success', mes)
          this.confirmLoading = false
          this.visible = false
          this.$emit('refresh')
          this.fileList = []
          this.fileArr = []
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    // 预览图片，显示大图
    handlePreview(file) {
      this.$refs.previewModal.show([file.savePath])
    },
    handleRemove(info, fileList) {
      console.log('remove info', info)
      this.fileList = [...fileList]
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          this.fileList.push(data)
          this.fileList[this.fileList.length - 1].status = 'done'
          this.fileList[this.fileList.length - 1].savePath = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          console.log('fileList', this.fileList)
        }
      })
    }
  }
}
</script>

<style scoped>
.w330 {
  width: 330px;
}
.avatar-uploader >>> .ant-upload-list-item {
  width: 180px;
  height: 180px;
  display: inline-block;
}
.avatar-uploader >>> .ant-upload {
  width: 180px;
  height: 180px;
}
</style>
